import datagrid from './datagrid';
import form from '../from/form';
import paging from './paging'
import checkList from './checkList';


var table = function (options) {
    if (!options) {
        options = {};
    };
    // 生成整体html
    this.html = $('<div class="FUI-table-layout" style="padding: 0"></div>');
    this.whereBox = $('<div class="layui-form-item"></div').appendTo(this.html);

    this.tableElement = $('<div></div>').appendTo(this.html);
    this.pagingElement = $('<div class="layout-table-paging"></div>').appendTo(this.html);
    this.event = {
        error: function () { },
        scrollError: function () { },
        searchEvent: function () { },
    };
    this.whereObject = new form.form({
        type: 'mergeByOldData',
        onError: (errorMessage, event, key) => {
            this.event.error(errorMessage, event, key);
        },
        onScrollError: function (errorMessage, event, key) {
            this.event.error(errorMessage, event, key);
        },
    });
    this.indexKey = options.indexKey || 'page';
    this.countKey = options.countKey || 'limit';
    this.dataKey = options.dataKey || 'data';
    this.totalKey = options.totalKey || 'count';

    this.whereButtons = options.whereButtons || [];
    this.rightButtons = options.rightButtons || [];

    this.whereObject.$setOptions(this.renderWhereTemplate(options.whereOptions || {}));


    this.whereButtonBox = $('<div class="layui-inline"></div>').appendTo(this.whereBox);
    this.rightButtonBox = $('<div class="layui-inline layui-btn-right"></div>').appendTo(this.whereBox);

    this.tableObject = new datagrid(options.tableOptions || {}, this);
    this.tableElement.append(this.tableObject.render());
    this.tableObject.setCols(options.cols || []);

    this.pagingOptions = $.extend({}, {
        hasQuick: true,
        limitPage: true,
        countPage: true,
        index: 1,
        count: 10,
    }, options.pagingOptions);

    this.SearchValue = {};
    // this.oldSearchValue = {};


    this.pagingObject = new paging({
        data: {
            pageInfo: {
                index: this.pagingOptions.index,
                count: this.pagingOptions.count,
            },
        },
        hasQuick: this.pagingOptions.hasQuick,
        limitPage: this.pagingOptions.limitPage,
        countPage: this.pagingOptions.countPage,
        ajaxEvent: (data, callback) => {
            var _data = {};
            _data = $.extend({}, data, this.SearchValue);
            this.whereObject.$formElementKey
            for (let i = 0; i < this.whereObject.$formElementKey.length; i++) {
                const element = this.whereObject.$formElementKey[i];
                if (!_data.hasOwnProperty(element)) {
                    _data[element] = null;
                }
            };
            _data[this.indexKey] = data.pageInfo.index;
            _data[this.countKey] = data.pageInfo.count;
            options.getEvent(_data, (res) => {
                callback({
                    "totalRecord": res[this.totalKey],
                    "list": res[this.dataKey],
                });
            });
        },
        success: (result) => {
            this.tableObject.set(result);
        }
    });
    this.renderWhereButton();
    this.screenStatus = false;
};

table.prototype.init = function () {
    this.pagingElement.append(this.pagingObject.render());
};

var bindEvent = function (ele, event, table) {
    if (typeof event == 'function') {
        ele.click(function () {
            event(table);
        });
    } else if (event == 'screen') {
        ele.click(function () {
            table[event](ele);
        });
    } else {
        ele.click(function () {
            table[event]();
        });
    };
};

// 渲染顶部右侧按钮
table.prototype.renderButtonTemplate = function (data) {
    if (data.template) {
        var html = $(data.template);
    } else {
        var iconString = data.icon ? ('<i class="buttonIcon ' + data.icon + '"></i>') : '';
        var html = $('<div class="layui-btn layui-btn-ys layui-btn-sm ' + data.class + '">' + iconString + data.name + '</div>');
    };
    return html;
};

table.prototype.renderWhereButton = function () {
    // 渲染事件方法
    for (let i = 0; i < this.whereButtons.length; i++) {
        const element = this.whereButtons[i];
        var html = this.renderButtonTemplate(element);
        this.whereButtonBox.append(html);
        bindEvent(html, element.event, this);
    };

    // this.rightButtion
    // 渲染右侧按钮
    for (let i = 0; i < this.rightButtons.length; i++) {
        const element = this.rightButtons[i];
        var html = this.renderButtonTemplate(element);
        this.rightButtonBox.append(html);
        bindEvent(html, element.event, this);
    };

};

table.prototype.search = function () {
    this.whereObject.$get((value) => {
        this.SearchValue = value;
    });

    this.pagingObject.refresh({
        pageInfo: {
            index: 1,
            count: 10,
        },
    });
};

table.prototype.refresh = function () {
    this.pagingObject.init();
};

table.prototype.reset = function () {
    this.SearchValue = {};
    this.whereObject.clearAll();
    this.pagingObject.refresh({
        pageInfo: {
            index: 1,
            count: 10,
        },
    });
};

table.prototype.print = function () {
    this.tableObject.print();
};

table.prototype.exportCSV = function () {
    this.tableObject.exportFile();
};

table.prototype.exportXLS = function () {
    this.tableObject.exportFile('xls');
};

table.prototype.getCheckBoxValue = function () {
    return this.tableObject.getCheckBoxValue();
};

table.prototype.getRadioValue = function () {
    return this.tableObject.getRadioValue();
};

table.prototype.on = function (str, event) {
    return this.tableObject.on(str, event);
};

table.prototype.screen = function (ele) {

    if (this.screenStatus) {
        return;
    } else {
        this.screenStatus = true;
    };
    var _this = this;

    ele.css({
        'position': 'relative',
    });
    var opBox = $('<div class="FUI-Table-screen"></div>');
    opBox.click(function (e) {
        e.stopPropagation();
        e.preventDefault();
    });
    var body = $('<div class="FUI-Table-screen-body"></div>');
    var footer = $('<div class="FUI-Table-screen-footer"></div>');

    var confirm = $('<div class="layui-btn layui-btn-ys layui-btn-sm FUI-Table-screen-Confirm">确认</div>');
    var cancel = $('<div class="layui-btn layui-btn-ys layui-btn-sm FUI-Table-screen-Cancel">取消</div>');

    var _checkList = new checkList({
        checkAll: false, // 是否显示全选
        getType: 'array',
        data: this.tableObject.objs.screen.getKeyValues(),
    });
    _checkList.set(this.tableObject.objs.screen.getShowKeyValue());
    body.append(_checkList.html);

    footer.append(confirm).append(cancel);
    ele.append(opBox);
    opBox.append(body).append(footer);


    cancel.click(function (e) {

        opBox.remove();
        _this.screenStatus = false;
        e.stopPropagation();
        e.preventDefault();
    });
    confirm.click(function (e) {

        _checkList.get(function (err, value) {
            _this.tableObject.ChangeCols(value)
        });
        opBox.remove();
        _this.screenStatus = false;
        e.stopPropagation();
        e.preventDefault();
    });
};


// 渲染input
table.prototype.renderWhereTemplate = function (options) {
    this.whereBox.empty();
    var tepl = function (data) {
        var haveText = data.labelText;
        var labelWidthStyle = data.labelWidth ? ('style="width:' + data.labelWidth + 'px"') : '';


        var html = $('<div class="layui-inline">' +
            '    <label ' + (haveText ? '' : 'style="display:none"') + ' class="layui-form-label" ' + labelWidthStyle + '>' + data.labelText + '</label>' +
            '    <div class="layui-input-inline"></div>' +
            '</div>');
        return $(html);
    };
    for (let i = 0; i < options.length; i++) {
        const element = options[i];
        var template = tepl(element);
        element.el = template.find('.layui-input-inline');
        this.whereBox.append(template);
    };
    return options;
};



export default table;